package org.gpswalker.sys.components;

import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

public class TemplateConfigurationSingleton {
    // Private constructor prevents instantiation from other classes
    private TemplateConfigurationSingleton() {
        initConfiguration();
    }

    /**
     * SingletonHolder is loaded on the first execution of
     * Singleton.getInstance() or the first access to SingletonHolder.INSTANCE,
     * not before.
     */
    private static class SingletonHolder {
        private static final TemplateConfigurationSingleton INSTANCE = new TemplateConfigurationSingleton();
    }

    public static TemplateConfigurationSingleton getInstance() {
        return SingletonHolder.INSTANCE;
    }

    // end of Singleton pattern

    protected Configuration cfgr;

    public void initConfiguration() {
        cfgr = new Configuration();
        try {
            cfgr
                    .setDirectoryForTemplateLoading(new File(
                            "./WEB-INF/templates"));
            cfgr.setObjectWrapper(new DefaultObjectWrapper());
        } catch (Exception e) {
            throw new NullPointerException(e.getMessage());
        }
    }

    private void internalProcessTemplate(HttpServletResponse res,
            Template temp, Map datamodel) {
        try {
            Writer out = new OutputStreamWriter(res.getOutputStream(), "UTF-8");
            temp.process(datamodel, out);
            out.flush();
        } catch (Exception e) {
            throw new NullPointerException(e.getMessage());
        }

    }

    public void processTemplate(String templateName,
            HttpServletResponse res, Map datamodel) {
        Template newtemp;
        try {
            newtemp = cfgr.getTemplate(templateName);
            internalProcessTemplate(res, newtemp, datamodel);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}
